package com.ctrip.ec.api.mobile.controller;

import com.ctrip.ec.api.mobile.aop.AuthLogin;
import com.ctrip.ec.api.mobile.common.PagerInfo;
import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;
import com.ctrip.ec.api.mobile.model.activity.ActivityModel;
import com.ctrip.ec.api.mobile.model.activity.CategoryModel;
import com.ctrip.ec.biz.dao.activity.ActivityDao;
import com.ctrip.ec.biz.dao.activity.ActivityImageDao;
import com.ctrip.ec.biz.dao.activity.ActivityShareDao;
import com.ctrip.ec.biz.dao.brand.BrandDao;
import com.ctrip.ec.biz.dao.dict.DictDao;
import com.ctrip.ec.biz.dao.forward.ForwardActivityDao;
import com.ctrip.ec.biz.entity.activity.ActivityEntity;
import com.ctrip.ec.biz.entity.activity.ActivityImageEntity;
import com.ctrip.ec.biz.entity.activity.ActivityShareEntity;
import com.ctrip.ec.biz.entity.brand.BrandEntity;
import com.ctrip.ec.biz.entity.dict.DictCategory;
import com.ctrip.ec.biz.entity.dict.DictEntity;
import com.ctrip.ec.biz.entity.forward.ForwardActivityEntity;
import com.ctrip.ec.dal.EntityBase;
import com.ctrip.ec.dal.IdConvert;
import com.ctrip.ec.dal.PagerSetting;
import com.google.common.base.Strings;
import jdk.nashorn.internal.ir.RuntimeNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by jiangzy on 2018/9/17.
 */
@RestController
@RequestMapping("activity")
public class AcitivityController {

    @Autowired
    private DictDao dict;

    @Autowired
    private ActivityDao activity;

    @Autowired
    private BrandDao brand;

    @Autowired
    private ActivityImageDao activityImage;

    @Autowired
    private ActivityShareDao activityShare;

    @Autowired
    private ForwardActivityDao forwardActivity;

    @Value("${imageDomain}")
    private String imageDomain;


    //@AuthLogin
    @GetMapping("category")
    public List<CategoryModel> category() throws SQLException {
        List<DictEntity> list = dict.list(DictCategory.activity_type);
        List<CategoryModel> modelList = new ArrayList<>();
        for (DictEntity entity : list) {
            CategoryModel model = new CategoryModel();
            model.copyFrom(entity);
            model.setHasNew(activity.hasNew(entity.getId()));
            modelList.add(model);
        }
        return modelList;
    }

    @GetMapping("detail")
    public ActivityModel detail(@RequestParam Long id) throws SQLException {
        ActivityEntity entity = activity.entity(id);
        if (entity == null) {
            return null;
        }
        ActivityModel model = new ActivityModel(entity);


        BrandEntity brandEntity = brand.entity(model.getBrandId());

        brandEntity.setLogoImageUrl(imageDomain + brandEntity.getLogoImageUrl());
        brandEntity.setBannerImageUrl(imageDomain + brandEntity.getBannerImageUrl());
        brandEntity.setCoverImageUrl(imageDomain + brandEntity.getCoverImageUrl());


        model.setBrand(brandEntity);

        List<ActivityImageEntity> imageList = activityImage.listByActivityId(model.getId());
        for (ActivityImageEntity imageEntity : imageList) {
            imageEntity.setImageUrl(this.imageDomain + imageEntity.getImageUrl());
        }

        model.setImageList(imageList);

        if(RequestContext.getAgentId()>0){ //小程序的
            ForwardActivityEntity forwardActivityEntity = forwardActivity.entity(RequestContext.getAgentId(),model.getId());
            if(forwardActivityEntity != null){
                model.setRemark(forwardActivityEntity.getRemark());
            }
        }
        return model;

    }

    @PostMapping("share")
    @AuthLogin
    public Long share(@RequestBody ActivityShareEntity shareEntity) throws SQLException {
        shareEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        shareEntity.setMemberId(RequestContext.getMemberId());
        if (shareEntity.getAddPrice() == null) {
            shareEntity.setAddPrice(new BigDecimal(0));
        }

        activityShare.save(shareEntity);
        return shareEntity.getId();
    }

    // @AuthLogin
    @GetMapping("list")
    public List<ActivityModel> list(@RequestParam(required = false) Long categoryId,
                                    @RequestParam(required = false) Long brandId,
                                    @RequestParam(required = false) Integer pageSize,
                                    @RequestParam(required = false) Integer pageIndex) throws SQLException {

        if (categoryId == null && brandId == null) {
            throw new ValidateException("缺少categoryId或brandId参数");
        }

        Timestamp now = new Timestamp(System.currentTimeMillis());

        String where = null;
        Long agentId = RequestContext.getAgentId();
        if (agentId == 0) {
            where = "end_time >= @0  and agent_id=0";
        } else {
            where = "end_time >= @0 and ((agent_id=0 and id in (select activity_id from " +
                    EntityBase.getTableName(ForwardActivityEntity.class) + " where agent_id=" + agentId + ")) or agent_id=" + agentId + ")";
        }
        if (categoryId != null) {
            where += " and category_id=" + categoryId;
        }
        if (brandId != null) {
            where += " and brand_id=" + brandId;
        }

        PagerSetting setting = new PagerSetting();

        if (pageIndex != null) {
            setting.setPageIndex(pageIndex);
        }
        if (pageSize != null) {
            setting.setPageSize(pageSize);
        }

        if (!Strings.isNullOrEmpty(where)) {
            setting.setWhere(where);
        }

        setting.setOrderBy("id desc");

        List<ActivityEntity> list = activity.list(setting, now);

        if (agentId > 0 && list.size()>0) { //如果是小程序需要替换描述
             String ids = IdConvert.join(list.stream().map(t->t.getId()).collect(Collectors.toList()));
             List<ForwardActivityEntity> forwardActivityList = forwardActivity.list("activity_id in (" + ids + ") and agent_id =" + agentId);

             for(ActivityEntity activityEntity : list){
                 Optional<ForwardActivityEntity> forwardActivityEntityOptional = forwardActivityList.stream().filter(t->t.getActivityId().equals(activityEntity.getId())).findFirst();
                 if(forwardActivityEntityOptional.isPresent()){
                     activityEntity.setRemark(forwardActivityEntityOptional.get().getRemark());
                 }
             }
        }


        List<ActivityModel> models = new ArrayList<>();
        for (ActivityEntity entity : list) {
            ActivityModel model = new ActivityModel(entity);

            List<ActivityImageEntity> imageList = activityImage.listByActivityId(entity.getId());
            for (ActivityImageEntity imageEntity : imageList) {
                imageEntity.setImageUrl(this.imageDomain + imageEntity.getImageUrl());
            }
            model.setImageList(imageList);
            model.setBrand(brand.entity(entity.getBrandId()));
            model.getBrand().setLogoImageUrl(this.imageDomain + model.getBrand().getLogoImageUrl());
            models.add(model);
        }

        RequestContext.setResponseHeaderPager(new PagerInfo(setting.getRecordCount(), setting.getPageIndex(), setting.getPageSize()));

        return models;
    }

}
